<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leetcode 题解 - 贪心思想 | Zhang Shuo'blog</title><meta name="keywords" content="Leetcode题解"><meta name="author" content="Zhang Shuo"><meta name="copyright" content="Zhang Shuo"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Leetcode 题解 - 贪心思想  Leetcode 题解 - 贪心思想 1. 分配饼干 2. 不重叠的区间个数 3. 投飞镖刺破气球 4. 根据身高和序号重组队列 5. 买卖股票最大的收益 6. 买卖股票的最大收益 II 7. 种植花朵 8. 判断是否为子序列 9. 修改一个数成为非递减数组 10. 子数组最大的和 11. 分隔字符串使同种字符出现在一起    保证每次操作都是局部最优的，并">
<meta property="og:type" content="article">
<meta property="og:title" content="Leetcode 题解 - 贪心思想">
<meta property="og:url" content="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E8%B4%AA%E5%BF%83%E6%80%9D%E6%83%B3/index.html">
<meta property="og:site_name" content="Zhang Shuo&#39;blog">
<meta property="og:description" content="Leetcode 题解 - 贪心思想  Leetcode 题解 - 贪心思想 1. 分配饼干 2. 不重叠的区间个数 3. 投飞镖刺破气球 4. 根据身高和序号重组队列 5. 买卖股票最大的收益 6. 买卖股票的最大收益 II 7. 种植花朵 8. 判断是否为子序列 9. 修改一个数成为非递减数组 10. 子数组最大的和 11. 分隔字符串使同种字符出现在一起    保证每次操作都是局部最优的，并">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://zhang-shuo-fr.gitee.io/hexo3/img/2.jpg">
<meta property="article:published_time" content="2021-12-06T09:36:00.000Z">
<meta property="article:modified_time" content="2021-12-10T12:57:38.860Z">
<meta property="article:author" content="Zhang Shuo">
<meta property="article:tag" content="Leetcode题解">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zhang-shuo-fr.gitee.io/hexo3/img/2.jpg"><link rel="shortcut icon" href="/hexo3/img/mao_tou_xiang.jpg"><link rel="canonical" href="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E8%B4%AA%E5%BF%83%E6%80%9D%E6%83%B3/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="manifest" href="/hexo3/pwa/manifest.json"/><link rel="apple-touch-icon" sizes="180x180" href="/hexo3/pwa/apple-touch-icon.png"/><link rel="icon" type="image/png" sizes="32x32" href="/hexo3/pwa/32.png"/><link rel="icon" type="image/png" sizes="16x16" href="/hexo3/pwa/16.png"/><link rel="mask-icon" href="/hexo3/pwa/safari-pinned-tab.svg" color="#5bbad5"/><link rel="stylesheet" href="/hexo3/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/hexo3/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Leetcode 题解 - 贪心思想',
  isPost: true,
  isHome: false,
  isHighlightShrink: undefined,
  isToc: true,
  postUpdate: '2021-12-10 20:57:38'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><style type="text/css">#toggle-sidebar {left:100px}</style><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/hexo3/img/mao_tou_xiang.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/archives/"><div class="headline">文章</div><div class="length-num">176</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/tags/"><div class="headline">标签</div><div class="length-num">45</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexo3/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 小窝</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexo3/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/hexo3/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/hexo3/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexo3/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/hexo3/img/2.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/hexo3/">Zhang Shuo'blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexo3/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 小窝</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexo3/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/hexo3/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/hexo3/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexo3/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Leetcode 题解 - 贪心思想</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-06T09:36:00.000Z" title="发表于 2021-12-06 17:36:00">2021-12-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-12-10T12:57:38.860Z" title="更新于 2021-12-10 20:57:38">2021-12-10</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/hexo3/categories/Leetcode%E9%A2%98%E8%A7%A3/">Leetcode题解</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Leetcode 题解 - 贪心思想"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Leetcode-题解-贪心思想"><a href="#Leetcode-题解-贪心思想" class="headerlink" title="Leetcode 题解 - 贪心思想"></a>Leetcode 题解 - 贪心思想</h1><!-- GFM-TOC -->
<ul>
<li><a href="#leetcode-%E9%A2%98%E8%A7%A3---%E8%B4%AA%E5%BF%83%E6%80%9D%E6%83%B3">Leetcode 题解 - 贪心思想</a><ul>
<li><a href="#1-%E5%88%86%E9%85%8D%E9%A5%BC%E5%B9%B2">1. 分配饼干</a></li>
<li><a href="#2-%E4%B8%8D%E9%87%8D%E5%8F%A0%E7%9A%84%E5%8C%BA%E9%97%B4%E4%B8%AA%E6%95%B0">2. 不重叠的区间个数</a></li>
<li><a href="#3-%E6%8A%95%E9%A3%9E%E9%95%96%E5%88%BA%E7%A0%B4%E6%B0%94%E7%90%83">3. 投飞镖刺破气球</a></li>
<li><a href="#4-%E6%A0%B9%E6%8D%AE%E8%BA%AB%E9%AB%98%E5%92%8C%E5%BA%8F%E5%8F%B7%E9%87%8D%E7%BB%84%E9%98%9F%E5%88%97">4. 根据身高和序号重组队列</a></li>
<li><a href="#5-%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E6%9C%80%E5%A4%A7%E7%9A%84%E6%94%B6%E7%9B%8A">5. 买卖股票最大的收益</a></li>
<li><a href="#6-%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E5%A4%A7%E6%94%B6%E7%9B%8A-ii">6. 买卖股票的最大收益 II</a></li>
<li><a href="#7-%E7%A7%8D%E6%A4%8D%E8%8A%B1%E6%9C%B5">7. 种植花朵</a></li>
<li><a href="#8-%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E4%B8%BA%E5%AD%90%E5%BA%8F%E5%88%97">8. 判断是否为子序列</a></li>
<li><a href="#9-%E4%BF%AE%E6%94%B9%E4%B8%80%E4%B8%AA%E6%95%B0%E6%88%90%E4%B8%BA%E9%9D%9E%E9%80%92%E5%87%8F%E6%95%B0%E7%BB%84">9. 修改一个数成为非递减数组</a></li>
<li><a href="#10-%E5%AD%90%E6%95%B0%E7%BB%84%E6%9C%80%E5%A4%A7%E7%9A%84%E5%92%8C">10. 子数组最大的和</a></li>
<li><a href="#11-%E5%88%86%E9%9A%94%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%BD%BF%E5%90%8C%E7%A7%8D%E5%AD%97%E7%AC%A6%E5%87%BA%E7%8E%B0%E5%9C%A8%E4%B8%80%E8%B5%B7">11. 分隔字符串使同种字符出现在一起</a><!-- GFM-TOC --></li>
</ul>
</li>
</ul>
<p>保证每次操作都是局部最优的，并且最后得到的结果是全局最优的。</p>
<h2 id="1-分配饼干"><a href="#1-分配饼干" class="headerlink" title="1. 分配饼干"></a>1. 分配饼干</h2><p>455. Assign Cookies (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/assign-cookies/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/assign-cookies/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: grid[1,3], size[1,2,4]</span><br><span class="line">Output: 2</span><br></pre></td></tr></table></figure>

<p>题目描述：每个孩子都有一个满足度 grid，每个饼干都有一个大小 size，只有饼干的大小大于等于一个孩子的满足度，该孩子才会获得满足。求解最多可以获得满足的孩子数量。</p>
<ol>
<li>给一个孩子的饼干应当尽量小并且又能满足该孩子，这样大饼干才能拿来给满足度比较大的孩子。</li>
<li>因为满足度最小的孩子最容易得到满足，所以先满足满足度最小的孩子。</li>
</ol>
<p>在以上的解法中，我们只在每次分配时饼干时选择一种看起来是当前最优的分配方法，但无法保证这种局部最优的分配方法最后能得到全局最优解。我们假设能得到全局最优解，并使用反证法进行证明，即假设存在一种比我们使用的贪心策略更优的最优策略。如果不存在这种最优策略，表示贪心策略就是最优策略，得到的解也就是全局最优解。</p>
<p>证明：假设在某次选择中，贪心策略选择给当前满足度最小的孩子分配第 m 个饼干，第 m 个饼干为可以满足该孩子的最小饼干。假设存在一种最优策略，可以给该孩子分配第 n 个饼干，并且 m &lt; n。我们可以发现，经过这一轮分配，贪心策略分配后剩下的饼干一定有一个比最优策略来得大。因此在后续的分配中，贪心策略一定能满足更多的孩子。也就是说不存在比贪心策略更优的策略，即贪心策略就是最优策略。</p>
<div align="center"> <img src= "" data-lazy-src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e69537d2-a016-4676-b169-9ea17eeb9037.gif" width="430px"> </div><br>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">findContentChildren</span><span class="params">(<span class="keyword">int</span>[] grid, <span class="keyword">int</span>[] size)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (grid == <span class="keyword">null</span> || size == <span class="keyword">null</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    Arrays.sort(grid);</span><br><span class="line">    Arrays.sort(size);</span><br><span class="line">    <span class="keyword">int</span> gi = <span class="number">0</span>, si = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (gi &lt; grid.length &amp;&amp; si &lt; size.length) &#123;</span><br><span class="line">        <span class="keyword">if</span> (grid[gi] &lt;= size[si]) &#123;</span><br><span class="line">            gi++;</span><br><span class="line">        &#125;</span><br><span class="line">        si++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> gi;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-不重叠的区间个数"><a href="#2-不重叠的区间个数" class="headerlink" title="2. 不重叠的区间个数"></a>2. 不重叠的区间个数</h2><p>435. Non-overlapping Intervals (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/non-overlapping-intervals/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/non-overlapping-intervals/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: [ [1,2], [1,2], [1,2] ]</span><br><span class="line"></span><br><span class="line">Output: 2</span><br><span class="line"></span><br><span class="line">Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.</span><br></pre></td></tr></table></figure>

<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: [ [1,2], [2,3] ]</span><br><span class="line"></span><br><span class="line">Output: 0</span><br><span class="line"></span><br><span class="line">Explanation: You don&#x27;t need to remove any of the intervals since they&#x27;re already non-overlapping.</span><br></pre></td></tr></table></figure>

<p>题目描述：计算让一组区间不重叠所需要移除的区间个数。</p>
<p>先计算最多能组成的不重叠区间个数，然后用区间总个数减去不重叠区间的个数。</p>
<p>在每次选择中，区间的结尾最为重要，选择的区间结尾越小，留给后面的区间的空间越大，那么后面能够选择的区间个数也就越大。</p>
<p>按区间的结尾进行排序，每次选择结尾最小，并且和前一个区间不重叠的区间。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">eraseOverlapIntervals</span><span class="params">(<span class="keyword">int</span>[][] intervals)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (intervals.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    Arrays.sort(intervals, Comparator.comparingInt(o -&gt; o[<span class="number">1</span>]));</span><br><span class="line">    <span class="keyword">int</span> cnt = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> end = intervals[<span class="number">0</span>][<span class="number">1</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; intervals.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (intervals[i][<span class="number">0</span>] &lt; end) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        end = intervals[i][<span class="number">1</span>];</span><br><span class="line">        cnt++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> intervals.length - cnt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用 lambda 表示式创建 Comparator 会导致算法运行时间过长，如果注重运行时间，可以修改为普通创建 Comparator 语句：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Arrays.sort(intervals, <span class="keyword">new</span> Comparator&lt;<span class="keyword">int</span>[]&gt;() &#123;</span><br><span class="line">     <span class="meta">@Override</span></span><br><span class="line">     <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(<span class="keyword">int</span>[] o1, <span class="keyword">int</span>[] o2)</span> </span>&#123;</span><br><span class="line">         <span class="keyword">return</span> (o1[<span class="number">1</span>] &lt; o2[<span class="number">1</span>]) ? -<span class="number">1</span> : ((o1[<span class="number">1</span>] == o2[<span class="number">1</span>]) ? <span class="number">0</span> : <span class="number">1</span>);</span><br><span class="line">     &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>实现 compare() 函数时避免使用 <code>return o1[1] - o2[1];</code> 这种减法操作，防止溢出。</p>
<h2 id="3-投飞镖刺破气球"><a href="#3-投飞镖刺破气球" class="headerlink" title="3. 投飞镖刺破气球"></a>3. 投飞镖刺破气球</h2><p>452. Minimum Number of Arrows to Burst Balloons (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/description/">力扣</a></p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line">[[10,16], [2,8], [1,6], [7,12]]</span><br><span class="line"></span><br><span class="line">Output:</span><br><span class="line">2</span><br></pre></td></tr></table></figure>

<p>题目描述：气球在一个水平数轴上摆放，可以重叠，飞镖垂直投向坐标轴，使得路径上的气球都被刺破。求解最小的投飞镖次数使所有气球都被刺破。</p>
<p>也是计算不重叠的区间个数，不过和 Non-overlapping Intervals 的区别在于，[1, 2] 和 [2, 3] 在本题中算是重叠区间。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">findMinArrowShots</span><span class="params">(<span class="keyword">int</span>[][] points)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (points.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    Arrays.sort(points, Comparator.comparingInt(o -&gt; o[<span class="number">1</span>]));</span><br><span class="line">    <span class="keyword">int</span> cnt = <span class="number">1</span>, end = points[<span class="number">0</span>][<span class="number">1</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; points.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (points[i][<span class="number">0</span>] &lt;= end) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        cnt++;</span><br><span class="line">        end = points[i][<span class="number">1</span>];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> cnt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="4-根据身高和序号重组队列"><a href="#4-根据身高和序号重组队列" class="headerlink" title="4. 根据身高和序号重组队列"></a>4. 根据身高和序号重组队列</h2><p>406. Queue Reconstruction by Height(Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/queue-reconstruction-by-height/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/queue-reconstruction-by-height/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input:</span><br><span class="line">[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]</span><br><span class="line"></span><br><span class="line">Output:</span><br><span class="line">[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]</span><br></pre></td></tr></table></figure>

<p>题目描述：一个学生用两个分量 (h, k) 描述，h 表示身高，k 表示排在前面的有 k 个学生的身高比他高或者和他一样高。</p>
<p>为了使插入操作不影响后续的操作，身高较高的学生应该先做插入操作，否则身高较小的学生原先正确插入的第 k 个位置可能会变成第 k+1 个位置。</p>
<p>身高 h 降序、个数 k 值升序，然后将某个学生插入队列的第 k 个位置中。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">int</span>[][] reconstructQueue(<span class="keyword">int</span>[][] people) &#123;</span><br><span class="line">    <span class="keyword">if</span> (people == <span class="keyword">null</span> || people.length == <span class="number">0</span> || people[<span class="number">0</span>].length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">0</span>][<span class="number">0</span>];</span><br><span class="line">    &#125;</span><br><span class="line">    Arrays.sort(people, (a, b) -&gt; (a[<span class="number">0</span>] == b[<span class="number">0</span>] ? a[<span class="number">1</span>] - b[<span class="number">1</span>] : b[<span class="number">0</span>] - a[<span class="number">0</span>]));</span><br><span class="line">    List&lt;<span class="keyword">int</span>[]&gt; queue = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span>[] p : people) &#123;</span><br><span class="line">        queue.add(p[<span class="number">1</span>], p);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> queue.toArray(<span class="keyword">new</span> <span class="keyword">int</span>[queue.size()][]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-买卖股票最大的收益"><a href="#5-买卖股票最大的收益" class="headerlink" title="5. 买卖股票最大的收益"></a>5. 买卖股票最大的收益</h2><p>121. Best Time to Buy and Sell Stock (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/">力扣</a></p>
<p>题目描述：一次股票交易包含买入和卖出，只进行一次交易，求最大收益。</p>
<p>只要记录前面的最小价格，将这个最小价格作为买入价格，然后将当前的价格作为售出价格，查看当前收益是不是最大收益。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">maxProfit</span><span class="params">(<span class="keyword">int</span>[] prices)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> n = prices.length;</span><br><span class="line">    <span class="keyword">if</span> (n == <span class="number">0</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> soFarMin = prices[<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">int</span> max = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; n; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (soFarMin &gt; prices[i]) soFarMin = prices[i];</span><br><span class="line">        <span class="keyword">else</span> max = Math.max(max, prices[i] - soFarMin);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> max;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h2 id="6-买卖股票的最大收益-II"><a href="#6-买卖股票的最大收益-II" class="headerlink" title="6. 买卖股票的最大收益 II"></a>6. 买卖股票的最大收益 II</h2><p>122. Best Time to Buy and Sell Stock II (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/description/">力扣</a></p>
<p>题目描述：可以进行多次交易，多次交易之间不能交叉进行，可以进行多次交易。</p>
<p>对于 [a, b, c, d]，如果有 a &lt;= b &lt;= c &lt;= d ，那么最大收益为 d - a。而 d - a = (d - c) + (c - b) + (b - a) ，因此当访问到一个 prices[i] 且 prices[i] - prices[i-1] &gt; 0，那么就把 prices[i] - prices[i-1] 添加到收益中。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">maxProfit</span><span class="params">(<span class="keyword">int</span>[] prices)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> profit = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; prices.length; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (prices[i] &gt; prices[i - <span class="number">1</span>]) &#123;</span><br><span class="line">            profit += (prices[i] - prices[i - <span class="number">1</span>]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> profit;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h2 id="7-种植花朵"><a href="#7-种植花朵" class="headerlink" title="7. 种植花朵"></a>7. 种植花朵</h2><p>605. Can Place Flowers (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/can-place-flowers/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/can-place-flowers/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: flowerbed = [1,0,0,0,1], n = 1</span><br><span class="line">Output: True</span><br></pre></td></tr></table></figure>

<p>题目描述：flowerbed 数组中 1 表示已经种下了花朵。花朵之间至少需要一个单位的间隔，求解是否能种下 n 朵花。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">canPlaceFlowers</span><span class="params">(<span class="keyword">int</span>[] flowerbed, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> len = flowerbed.length;</span><br><span class="line">    <span class="keyword">int</span> cnt = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; len &amp;&amp; cnt &lt; n; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (flowerbed[i] == <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> pre = i == <span class="number">0</span> ? <span class="number">0</span> : flowerbed[i - <span class="number">1</span>];</span><br><span class="line">        <span class="keyword">int</span> next = i == len - <span class="number">1</span> ? <span class="number">0</span> : flowerbed[i + <span class="number">1</span>];</span><br><span class="line">        <span class="keyword">if</span> (pre == <span class="number">0</span> &amp;&amp; next == <span class="number">0</span>) &#123;</span><br><span class="line">            cnt++;</span><br><span class="line">            flowerbed[i] = <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> cnt &gt;= n;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="8-判断是否为子序列"><a href="#8-判断是否为子序列" class="headerlink" title="8. 判断是否为子序列"></a>8. 判断是否为子序列</h2><p>392. Is Subsequence (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/is-subsequence/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/is-subsequence/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">s = &quot;abc&quot;, t = &quot;ahbgdc&quot;</span><br><span class="line">Return true.</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isSubsequence</span><span class="params">(String s, String t)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> index = -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">char</span> c : s.toCharArray()) &#123;</span><br><span class="line">        index = t.indexOf(c, index + <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">if</span> (index == -<span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="9-修改一个数成为非递减数组"><a href="#9-修改一个数成为非递减数组" class="headerlink" title="9. 修改一个数成为非递减数组"></a>9. 修改一个数成为非递减数组</h2><p>665. Non-decreasing Array (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/non-decreasing-array/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/non-decreasing-array/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: [4,2,3]</span><br><span class="line">Output: True</span><br><span class="line">Explanation: You could modify the first 4 to 1 to get a non-decreasing array.</span><br></pre></td></tr></table></figure>

<p>题目描述：判断一个数组是否能只修改一个数就成为非递减数组。</p>
<p>在出现 nums[i] &lt; nums[i - 1] 时，需要考虑的是应该修改数组的哪个数，使得本次修改能使 i 之前的数组成为非递减数组，并且   <strong>不影响后续的操作</strong>  。优先考虑令 nums[i - 1] = nums[i]，因为如果修改 nums[i] = nums[i - 1] 的话，那么 nums[i] 这个数会变大，就有可能比 nums[i + 1] 大，从而影响了后续操作。还有一个比较特别的情况就是 nums[i] &lt; nums[i - 2]，修改 nums[i - 1] = nums[i] 不能使数组成为非递减数组，只能修改 nums[i] = nums[i - 1]。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">checkPossibility</span><span class="params">(<span class="keyword">int</span>[] nums)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> cnt = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; nums.length &amp;&amp; cnt &lt; <span class="number">2</span>; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (nums[i] &gt;= nums[i - <span class="number">1</span>]) &#123;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        cnt++;</span><br><span class="line">        <span class="keyword">if</span> (i - <span class="number">2</span> &gt;= <span class="number">0</span> &amp;&amp; nums[i - <span class="number">2</span>] &gt; nums[i]) &#123;</span><br><span class="line">            nums[i] = nums[i - <span class="number">1</span>];</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            nums[i - <span class="number">1</span>] = nums[i];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> cnt &lt;= <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="10-子数组最大的和"><a href="#10-子数组最大的和" class="headerlink" title="10. 子数组最大的和"></a>10. 子数组最大的和</h2><p>53. Maximum Subarray (Easy)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/maximum-subarray/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/maximum-subarray/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">For example, given the array [-2,1,-3,4,-1,2,1,-5,4],</span><br><span class="line">the contiguous subarray [4,-1,2,1] has the largest sum = 6.</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">maxSubArray</span><span class="params">(<span class="keyword">int</span>[] nums)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (nums == <span class="keyword">null</span> || nums.length == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> preSum = nums[<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">int</span> maxSum = preSum;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; nums.length; i++) &#123;</span><br><span class="line">        preSum = preSum &gt; <span class="number">0</span> ? preSum + nums[i] : nums[i];</span><br><span class="line">        maxSum = Math.max(maxSum, preSum);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> maxSum;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="11-分隔字符串使同种字符出现在一起"><a href="#11-分隔字符串使同种字符出现在一起" class="headerlink" title="11. 分隔字符串使同种字符出现在一起"></a>11. 分隔字符串使同种字符出现在一起</h2><p>763. Partition Labels (Medium)</p>
<p><a target="_blank" rel="noopener" href="https://leetcode.com/problems/partition-labels/description/">Leetcode</a> / <a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/partition-labels/description/">力扣</a></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line">Input: S = &quot;ababcbacadefegdehijhklij&quot;</span><br><span class="line">Output: [9,7,8]</span><br><span class="line">Explanation:</span><br><span class="line">The partition is &quot;ababcbaca&quot;, &quot;defegde&quot;, &quot;hijhklij&quot;.</span><br><span class="line">This is a partition so that each letter appears in at most one part.</span><br><span class="line">A partition like &quot;ababcbacadefegde&quot;, &quot;hijhklij&quot; is incorrect, because it splits S into less parts.</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Integer&gt; <span class="title">partitionLabels</span><span class="params">(String S)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span>[] lastIndexsOfChar = <span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">26</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; S.length(); i++) &#123;</span><br><span class="line">        lastIndexsOfChar[char2Index(S.charAt(i))] = i;</span><br><span class="line">    &#125;</span><br><span class="line">    List&lt;Integer&gt; partitions = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="keyword">int</span> firstIndex = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (firstIndex &lt; S.length()) &#123;</span><br><span class="line">        <span class="keyword">int</span> lastIndex = firstIndex;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = firstIndex; i &lt; S.length() &amp;&amp; i &lt;= lastIndex; i++) &#123;</span><br><span class="line">            <span class="keyword">int</span> index = lastIndexsOfChar[char2Index(S.charAt(i))];</span><br><span class="line">            <span class="keyword">if</span> (index &gt; lastIndex) &#123;</span><br><span class="line">                lastIndex = index;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        partitions.add(lastIndex - firstIndex + <span class="number">1</span>);</span><br><span class="line">        firstIndex = lastIndex + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> partitions;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">char2Index</span><span class="params">(<span class="keyword">char</span> c)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> c - <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Zhang Shuo</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E8%B4%AA%E5%BF%83%E6%80%9D%E6%83%B3/">https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E8%B4%AA%E5%BF%83%E6%80%9D%E6%83%B3/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://zhang-shuo-fr.gitee.io/hexo3" target="_blank">Zhang Shuo'blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/hexo3/tags/Leetcode%E9%A2%98%E8%A7%A3/">Leetcode题解</a></div><div class="post_share"><div class="social-share" data-image="/hexo3/img/2.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/hexo3/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/hexo3/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/hexo3/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/hexo3/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E9%93%BE%E8%A1%A8/"><img class="prev-cover" src= "" data-lazy-src="/hexo3/img/18.jpg" onerror="onerror=null;src='/hexo3/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Leetcode 题解 - 链表</div></div></a></div><div class="next-post pull-right"><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E7%9B%AE%E5%BD%95/"><img class="next-cover" src= "" data-lazy-src="/hexo3/img/19.jpg" onerror="onerror=null;src='/hexo3/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Leetcode 题解 - 目录</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/" title="Leetcode 题解 - 二分查找"><img class="cover" src= "" data-lazy-src="/hexo3/img/1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 二分查找</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E4%BD%8D%E8%BF%90%E7%AE%97/" title="Leetcode 题解 - 位运算"><img class="cover" src= "" data-lazy-src="/hexo3/img/18.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 位运算</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%88%86%E6%B2%BB/" title="Leetcode 题解 - 分治"><img class="cover" src= "" data-lazy-src="/hexo3/img/8.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 分治</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%8F%8C%E6%8C%87%E9%92%88/" title="Leetcode 题解 - 双指针"><img class="cover" src= "" data-lazy-src="/hexo3/img/1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 双指针</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%93%88%E5%B8%8C%E8%A1%A8/" title="Leetcode 题解 - 哈希表"><img class="cover" src= "" data-lazy-src="/hexo3/img/12.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 哈希表</div></div></a></div><div><a href="/hexo3/2021/12/06/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%9B%BE/" title="Leetcode 题解 - 图"><img class="cover" src= "" data-lazy-src="/hexo3/img/19.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-06</div><div class="title">Leetcode 题解 - 图</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Leetcode-%E9%A2%98%E8%A7%A3-%E8%B4%AA%E5%BF%83%E6%80%9D%E6%83%B3"><span class="toc-number">1.</span> <span class="toc-text">Leetcode 题解 - 贪心思想</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E5%88%86%E9%85%8D%E9%A5%BC%E5%B9%B2"><span class="toc-number">1.1.</span> <span class="toc-text">1. 分配饼干</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E4%B8%8D%E9%87%8D%E5%8F%A0%E7%9A%84%E5%8C%BA%E9%97%B4%E4%B8%AA%E6%95%B0"><span class="toc-number">1.2.</span> <span class="toc-text">2. 不重叠的区间个数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E6%8A%95%E9%A3%9E%E9%95%96%E5%88%BA%E7%A0%B4%E6%B0%94%E7%90%83"><span class="toc-number">1.3.</span> <span class="toc-text">3. 投飞镖刺破气球</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E6%A0%B9%E6%8D%AE%E8%BA%AB%E9%AB%98%E5%92%8C%E5%BA%8F%E5%8F%B7%E9%87%8D%E7%BB%84%E9%98%9F%E5%88%97"><span class="toc-number">1.4.</span> <span class="toc-text">4. 根据身高和序号重组队列</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E6%9C%80%E5%A4%A7%E7%9A%84%E6%94%B6%E7%9B%8A"><span class="toc-number">1.5.</span> <span class="toc-text">5. 买卖股票最大的收益</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E5%A4%A7%E6%94%B6%E7%9B%8A-II"><span class="toc-number">1.6.</span> <span class="toc-text">6. 买卖股票的最大收益 II</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-%E7%A7%8D%E6%A4%8D%E8%8A%B1%E6%9C%B5"><span class="toc-number">1.7.</span> <span class="toc-text">7. 种植花朵</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E4%B8%BA%E5%AD%90%E5%BA%8F%E5%88%97"><span class="toc-number">1.8.</span> <span class="toc-text">8. 判断是否为子序列</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-%E4%BF%AE%E6%94%B9%E4%B8%80%E4%B8%AA%E6%95%B0%E6%88%90%E4%B8%BA%E9%9D%9E%E9%80%92%E5%87%8F%E6%95%B0%E7%BB%84"><span class="toc-number">1.9.</span> <span class="toc-text">9. 修改一个数成为非递减数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-%E5%AD%90%E6%95%B0%E7%BB%84%E6%9C%80%E5%A4%A7%E7%9A%84%E5%92%8C"><span class="toc-number">1.10.</span> <span class="toc-text">10. 子数组最大的和</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#11-%E5%88%86%E9%9A%94%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%BD%BF%E5%90%8C%E7%A7%8D%E5%AD%97%E7%AC%A6%E5%87%BA%E7%8E%B0%E5%9C%A8%E4%B8%80%E8%B5%B7"><span class="toc-number">1.11.</span> <span class="toc-text">11. 分隔字符串使同种字符出现在一起</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer" style="background-image: url('/hexo3/img/2.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By Zhang Shuo</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">簡</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/hexo3/js/utils.js"></script><script src="/hexo3/js/main.js"></script><script src="/hexo3/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/hexo3/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><div class="aplayer no-destroy" data-id="000PeZCQ1i4XVs" data-server="tencent" data-type="artist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>